<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { addPerson,delPerson,getPersonInfo,updatePerson}  from '/@/api/busi/dept'

  import { useMessage } from '/@/hooks/web/useMessage';

  //import { TreeItem } from '/@/components/Tree';
/* 
  import { getMenuList } from '/@/api/busi/corp'; */

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      //const treeData = ref<TreeItem[]>([]);
      const { createSuccessModal } = useMessage();
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
/*         if (unref(treeData).length === 0) {
          treeData.value = (await getMenuList()) as any as TreeItem[];
        } */
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增人员' : '编辑人员'));

      async function handleSubmit() {
        try {
          const values = await validate();
          if (!values.name) {
            return false;
          }
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          console.log('values', values);
          let res = null;
          if (!unref(isUpdate)) {
            res = await addPerson(values);
            createSuccessModal({
              content: `新增人员成功`,
            });
          } else {
            res = await updatePerson(values);
            createSuccessModal({
              content: `编辑人员成功`,
            });
          }
          console.log(res);
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        //treeData,
      };
    },
  });
</script>
